package com.yzh.wanandroid.vm

import android.app.Application
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import com.yzh.wanandroid.base.BaseFragmentViewModel
import com.yzh.wanandroid.model.LoginUserData
import com.yzh.wanandroid.model.StateData
import com.yzh.wanandroid.model.UserData
import com.yzh.wanandroid.network.retrofit.responsebean.BaseData
import com.yzh.wanandroid.network.retrofit.responsebean.UserInfo
import com.yzh.wanandroid.utils.IS_LOGIN
import com.yzh.wanandroid.utils.NIGHT_MODE
import com.yzh.wanandroid.utils.SpUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainFragmentVm(application: Application) : BaseFragmentViewModel(application) {

    private val TAG = "MainFragmentVm"

    private val loginUserData = LoginUserData()

    private lateinit var mOwner: LifecycleOwner

    val userLogin = MutableLiveData<LoginUserData>()

    val logOutState = MutableLiveData<Int>()

    fun isLogin() = SpUtils.getBoolean(IS_LOGIN, false)

    override fun onCreate(owner: LifecycleOwner) {
        this.mOwner = owner
        EventBus.getDefault().register(this)
        loadLocalData()
        loadDataFirst(owner)
    }

    /**
     *  第一步，获取保存下来的信息，防止网络延迟造成的信息更新慢
     */
    private fun loadLocalData() {
        userLogin.value = loginUserData
    }

    /**
     * 第二部，获取网络信息再更新一次
     */
    private fun loadDataFirst(owner: LifecycleOwner) {
        if (SpUtils.getBoolean(IS_LOGIN, false)) {
            loadUserInfo(owner)
        }
    }

    /**
     *  登录成功时
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun loginObserver(userData: UserData) {
        loginUserData.setSaveUsername(userData.userName)
        loadUserInfo(mOwner)
    }

    /**
     *  获取登录信息
     */
    private fun loadUserInfo(owner: LifecycleOwner) {
        var userInfoData = MutableLiveData<StateData<BaseData<UserInfo>>>()
        mUserRepository.loadUserInfo(owner,userInfoData)
        userInfoData.observe(owner) {
            it.data?.data?.level?.let { it1 -> loginUserData.setSaveLevel(it1) }
            it.data?.data?.rank?.let { it1 -> loginUserData.setSaveRank(it1) }
            userLogin.value = loginUserData
        }
    }

    /**
     * 退出登录
     */
    fun logOut(owner: LifecycleOwner) {
        mUserRepository.logOut(owner,logOutState)
        loginUserData.clear()
    }

    /**
     *  判断是否是夜间模式
     */
    fun isNightMode() = SpUtils.getBoolean(NIGHT_MODE, false)

    /**
     * 设置并保存夜间模式flag
     */
    fun chageNightMode(): Boolean {
        var modeFlag = !isNightMode()
        SpUtils.putBoolean(NIGHT_MODE, modeFlag)
        return modeFlag
    }

    override fun onDestory(owner: LifecycleOwner) {
        super.onDestory(owner)
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }
}